package org.meeting.radish.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CookieUtil {
    public static void addCookie(String key, String value, HttpServletResponse resp) {
        Cookie cookie = new Cookie(key, value);
        cookie.setPath("/");
        resp.addCookie(cookie);
    }

    public static Cookie addCookie(String key, String value, int liveTime) {
        Cookie cookie = new Cookie(key, value);
        cookie.setPath("/");
        cookie.setMaxAge(liveTime);
        return cookie;
    }

    public static Cookie getCookie(Cookie[] cookies, String cookieName) {
        if (cookieName == null || cookies == null || cookies.length == 0) {
            return null;
        }

        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)) {
                return cookie;
            }
        }

        return null;
    }

    public static void deleteCookie(HttpServletResponse resp, Cookie[] cookies) {
        if (resp == null || cookies == null || cookies.length == 0) {
            return;
        }
        for (Cookie cookie : cookies) {
            cookie.setMaxAge(0);
            resp.addCookie(cookie);
        }
    }

    public static void deleteCookie(HttpServletResponse resp, Cookie[] cookies, String cookieName) {
        if (resp == null || cookies == null || cookies.length == 0) {
            return;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)) {
                cookie.setMaxAge(0);
                resp.addCookie(cookie);
            }
        }
    }

    public static void deleteCookie(HttpServletResponse resp, Cookie[] cookies, String... cookieNames) {
        if (resp == null || cookies == null || cookies.length == 0) {
            return;
        }
        List<String> names = new ArrayList<>(Arrays.asList(cookieNames));
        deleteCookie(resp, cookies, names);
    }

    public static void deleteCookie(HttpServletResponse resp, Cookie[] cookies, List<String> cookieNames) {
        if (resp == null || cookies == null || cookies.length == 0) {
            return;
        }
        for (Cookie cookie : cookies) {
            if (cookieNames.contains(cookie.getName())) {
                cookie.setMaxAge(0);
                resp.addCookie(cookie);
            }
        }
    }
}
